<template>
  <div class="white-content" v-loading="pageLoading" element-loading-text="loading">
    <div class="newPageTitle">
      <span class="backIcon" @click="goBack"><i class="el-icon-back"></i></span>
      <h1 style="display:inline-block;margin-left:10px">{{isAdd?'添加':'修改'}}类目III</h1>
    </div>
    <el-form :model="datas" :rules="rules" ref="dataForm" label-width="130px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="类目II名称:" prop="parentName">
            <el-input v-model="datas.parentName" disabled placeholder=""></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="类目III名称:" prop="catalogName">
            <el-input v-model="datas.catalogName" @input="datas.catalogName=datas.catalogName.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')" placeholder="" maxlength="10" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="类目III描述:" prop="catalogDesc">
            <el-input v-model="datas.catalogDesc" @input="datas.catalogDesc=datas.catalogDesc.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')" placeholder="" maxlength="100" show-word-limit></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="税率:" prop="taxRate">
            <el-input type="number" v-model="datas.taxRate" @blur="onTaxRate(datas.taxRate)" :max="6" placeholder="例：6" @input="datas.taxRate=datas.taxRate.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')">
            <template slot="suffix">%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="税收分类编码:" prop="taxClassifyNo">
            <el-input type="text" v-model="datas.taxClassifyNo" @input="datas.taxRate=datas.taxRate.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="属性:">
            <span style="color: #929292;padding-right: 20px">{{ datas.attrList.length }}</span>
            <el-button @click="onDelete" :disabled="delDisabled" class="white-btn">删除</el-button>
            <el-button @click="onAdd" class="search-btn">添加</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div style="margin: 20px 0">
      <el-table
        :data="datas.attrList"
        @selection-change="delSelectionChange"
        size="mini"
      >
        <el-table-column
          type="selection"
          width="50"
          align="center"
          size="mini"
          label-class-name="table-selection"
        >
        </el-table-column>
        <el-table-column type="index" label="NO." align="center" min-width="55px"></el-table-column>
        <el-table-column
          label="属性名称"
          align="center"
          min-width="120"
          prop="attributeName"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          label="是否必须"
          align="center"
          min-width="120"
          prop="required"
          :show-overflow-tooltip="true"
        >
         <template slot-scope="scope">
           <span>{{ scope.row.required == 0 ? '否' : '是' }}</span>
         </template>
        </el-table-column>
        <el-table-column
          label="属性类型"
          align="center"
          min-width="120"
          prop="attributeType"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">{{ getDictionaryNameByCode('SPUATTRIBUTE', scope.row.attributeType) }}</template>
        </el-table-column>
        <el-table-column
          label="类目数量"
          align="center"
          min-width="120"
          prop="catalogCount"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column label="更新时间" align="center" min-width="130px" :show-overflow-tooltip="true">
          <template slot-scope="scope">{{
              scope.row.updateTime | timestampToChange('time')
            }}</template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <div class="footer-btn">
        <el-button @click="goBack" class="white-btn">取消</el-button>
        <el-button
          @click="onCheck"
          class="search-btn"
          :loading="submitting"
          :disabled="!isUpdate"
        >保存</el-button>
      </div>
    </div>
    <dialog-table ref="dialogTable"></dialog-table>
  </div>
</template>

<script>
import { xor } from 'lodash'
import { getDetail, catalogUpdate } from '@/api/catalog'
import { setRouterParams, getRouterParams } from '@/utils/auth'
import DialogTable from './dialogTable.vue'
import { mapGetters } from 'vuex'
import { common } from '@/mixins/common'
export default {
  name: 'threeCatalog',
  components: { DialogTable },
  mixins: [common],
  data () {
    return {
      datas: {
        parentName: '',
        catalogName: '',
        catalogDesc: '',
        parentId: '',
        catalogLevel: 3,
        taxRate: '',
        id: '',
        taxClassifyNo: '',
        attrList: []
      },
      rules: {
        catalogName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        catalogDesc: [{ required: true, message: '描述不能为空', trigger: 'blur' }],
        taxRate: [{ required: true, message: '税率不能为空', trigger: 'blur' }],
        taxClassifyNo: [{ required: true, message: '税收分类编码不能为空', trigger: 'blur' }]
      },
      delSelectData: [],
      delDisabled: true,
      isAdd: true,
      level: '',
      id: '',
      isUpdate: '',
      submitting: false,
      pageLoading: false
    }
  },
  watch: {
    datas: {
      handler () {
        this.isUpdate = true
      },
      deep: true
    }
  },
  computed: {
    ...mapGetters(['lookupItems'])
  },
  mounted () {
    let params = {}
    if (Number(this.$route.params.level) >= 0) {
      params = this.$route.params
      setRouterParams(this.$route)
    } else {
      params = getRouterParams(this.$route)
    }
    this.level = params.level
    if (params.id) {
      this.isAdd = false
      this.datas.id = params.id
      this.getDetails()
    }
    if (Number(params.parentId) >= 0) {
      this.isAdd = true
      this.datas.parentId = params.parentId
      this.getParent(params.parentId)
    }
    this.$nextTick(() => {
      this.isUpdate = false
    })
  },
  methods: {
    onTaxRate (val) {
      if (parseInt(val) > 999999) {
        this.$alert('最高税率不能超过6位数')
        this.datas.taxRate = ''
      }
    },
    getParent (id) {
      this.pageLoading = true
      getDetail(id).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            this.datas.parentName = res.obj.catalogName
            this.$nextTick(() => {
              this.isUpdate = false
            })
          } else {
            this.$alert(this.$t(res.code))
          }
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    getDetails () {
      this.pageLoading = true
      getDetail(this.datas.id).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            this.datas = res.obj
            this.datas.taxRate = (res.obj.taxRate * 100).toFixed(2)
            this.$nextTick(() => {
              this.isUpdate = false
            })
          } else {
            this.$alert(this.$t(res.code))
          }
          this.pageLoading = false
        }
      }).catch(() => {
        this.pageLoading = false
      })
    },
    onAdd () {
      const idList = []
      if (this.datas.attrList && this.datas.attrList.length > 0) {
        this.datas.attrList.forEach(item => {
          idList.push(item.id)
        })
      }
      this.$refs.dialogTable.open(idList)
    },
    goBack () {
      if (this.isUpdate) {
        this.$confirm('确定离开此页面？如果离开，更改将丢失', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$router.push({ name: 'CatalogIndex', params: { keep: true } })
        })
      } else {
        this.$router.push({ name: 'CatalogIndex', params: { keep: true } })
      }
    },
    onCheck () {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.onSubmit()
        }
      })
    },
    onSubmit () {
      this.datas.attributeIdList = []
      const attrList = this.datas.attrList
      if (attrList.length < 1 || !attrList) {
        this.$alert('请至少添加一条属性')
        return false
      }
      attrList.forEach(item => {
        this.datas.attributeIdList.push(item.id)
      })
      for (var i = 0; i < 4 - Number(this.level); i++) {
        const childSelectId = sessionStorage.getItem('select' + Number(this.level + i))
        if (childSelectId) {
          sessionStorage.removeItem('select' + Number(this.level + i))
        }
      }
      this.submitting = true
      const newTaxRate = this.datas.taxRate / 100
      const params = {
        ...this.datas,
        taxRate: newTaxRate
      }
      catalogUpdate(params).then(res => {
        if (res) {
          if (Number(res.code) === 1) {
            sessionStorage.setItem('select' + this.level, this.datas.id)
            this.$alert('成功', {
              confirmButtonText: '确定',
              callback: action => {
                this.$router.push({ name: 'CatalogIndex', params: { keep: true } })
              }
            })
          } else {
            this.$alert(this.$t(res.code))
          }
          this.submitting = false
        }
      }).catch(() => {
        this.submitting = false
      })
    },
    delSelectionChange (val) { // 删除选择
      this.delSelectData = val
      if (val.length > 0) {
        this.delDisabled = false
      } else {
        this.delDisabled = true
      }
    },
    onDelete () {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.datas.attrList = xor(this.datas.attrList, this.delSelectData)
        this.$alert('删除成功')
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.footer {
  width: 100%;
  margin: 0;
}
</style>
<style>
.el-input input::-webkit-outer-spin-button,
.el-input input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
.el-input input[type='number']{
  -moz-appearance: textfield;
}
</style>
